<!doctype html>
<!--
Copyright 2018 Google, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

<style>
main {
  width: 500px;
  height: 500px;
  outline: 1px solid black;

  display: layout(random);
}

div {
  width: 200px;
  height: 200px;
  background-color: hotpink;
}

</style>

<main>
  <div>A</div>
  <div>B</div>
  <div>C</div>
  <div>D</div>
</main>

<script language="javascript+layout">
  registerLayout("random", class {
    // currently: all children are blockified
    async intrinsicSizes() {}
    async layout(children, edges, constraintSpace, styles) {
      const childFragments = []
      console.log(constraintSpace);
      for(const child of children) {
        const childFragment = await child.layoutNextFragment();
        console.log(childFragment);
        childFragment.inlineOffset = Math.random() * constraintSpace.fixedInlineSize;
        childFragment.blockOffset = Math.random() * constraintSpace.fixedBlockSize;
        childFragments.push(childFragment);
      }

      return {
        childFragments
      };
    }
  });
</script>
<script>
  if(!('layoutWorklet' in CSS)) {
    document.write('You need Custom Layout for this demo :(');
  }
  function urlFromTag(sel) {
    const el = document.querySelector(sel);
    if(!el) {
      throw new Error("Couldn’t find element");
    }
    const blob = new Blob([el.textContent], {type: "text/javascript"});
    return URL.createObjectURL(blob);
  }
  async function init() {
    await CSS.layoutWorklet.addModule(urlFromTag("script[language='javascript+layout']"));
  }
  init();
</script>
